#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <sys/wait.h>

char g_Command[1024];

int GetCommand()
{
    memset(g_Command, 0, sizeof(g_Command));
    printf("[minishell@localhost]$");
    fflush(stdout);
    
    if(fgets(g_Command, sizeof(g_Command) - 1, stdin) == NULL)
    {
        printf("fgets");
        return -1;
    }
    printf("%s\n", g_Command);
    return 0;
}


int ExecCommand(int argc, char* argv[])
{
    pid_t pid = fork();
    if(pid < 0)
    {
        perror("fork");
        return -1;
    }
    else if(pid == 0)
    {
        //child
        execvp(argv[0], argv);
        exit(1);
    }
    else
    {
        //father
        waitpid(pid, NULL, 0);
    }
    return 0;
}

int DealCommand(char* command)
{
    //将拿到的命令以空格分隔出来
    int argc = 0;
    char* argv[32];
    while(*command)
    {
        if(!isspace(*command))
        {
            argv[argc] = command;
            argc++;
            while(!isspace(*command) && *command != '\0')
            {
                command++;
            }
            *command = '\0';
        }
        command++;
    }

    argv[argc] = NULL;
    for(int i = 0; i < argc; i++)
    {
        printf("%s\n", argv[i]);
    }

    ExecCommand(argc, argv);
    return 0;
}



int main()
{
    //获取输入，解析输入，处理输入
    while(1)
    {
        if(GetCommand() != 0)
        {
            continue;
        }
        //处理获取到的命令
        DealCommand(g_Command);
    }
    return 0;
}
